<template>
  <div class="container mt-5">
    <div class="row justify-content-center">
      <div class="col-md-6">
        <div class="card">
          <div class="card-header bg-success text-white">用户注册</div>
          <div class="card-body">
            <form @submit.prevent="handleRegister">
              <div class="mb-3">
                <label for="username" class="form-label">用户名</label>
                <input 
                  type="text" 
                  id="username" 
                  class="form-control" 
                  v-model="form.username"
                  required
                >
              </div>
              
              <div class="mb-3">
                <label for="password" class="form-label">密码</label>
                <input 
                  type="password" 
                  id="password" 
                  class="form-control" 
                  v-model="form.password"
                  required
                >
              </div>
              
              <button 
                type="submit" 
                class="btn btn-success w-100"
                :disabled="isLoading"
              >
                {{ isLoading ? '注册中...' : '注册' }}
              </button>
              
              <div class="mt-3 text-danger" v-if="error">{{ error }}</div>
              <div class="mt-3 text-muted" v-if="!error && registerSuccess">注册成功，请登录！</div>
            </form>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { useAuthStore } from '@/stores/auth';
import { useRouter } from 'vue-router';

const authStore = useAuthStore();
const router = useRouter();

const form = ref({
  username: '',
  password: ''
});
const error = ref('');
const isLoading = ref(false);
const registerSuccess = ref(false);

const handleRegister = async () => {
  error.value = '';
  isLoading.value = true;

  const success = await authStore.register(
    form.value.username, 
    form.value.password
  );

  if (success) {
    registerSuccess.value = true;
    // 注册成功后，可跳转到登录页面，这里也可以延迟跳转等，根据需求调整
    setTimeout(() => {
      router.push('/login');
    }, 1500);
  } else {
    error.value = authStore.error || '注册失败，请重试';
  }

  isLoading.value = false;
};
</script>